/*
 * Timer.c
 *
 * Created: 15/12/2013 12:22:33
 *  Author: Psychic
 */ 
// ---------------------------------------------------------------------------
// Core Arduino Libraries
#include "Arduino.h"
// Integer types
#include "stdint.h"
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Arduino UNO Clock Speed = 16Mhz
#define ARDUINO_CLOCK_FREQUENCY (16000000)
// ---------------------------------------------------------------------------
boolean at_PwmTick;
boolean at_LedTick;
uint8_t at_InterruptCount;
uint8_t at_MsCount;
uint8_t at_Ms100Count;
// ---------------------------------------------------------------------------
void me_SetupTimer( )
{
	at_PwmTick = false;
	at_LedTick = false;
	at_InterruptCount = 0;
	at_MsCount = 0;
	at_Ms100Count = 0;
	
    // initialize timer1
    noInterrupts();           // disable all interrupts
    TCCR1A = 0; // Reset Timer 1
    TCCR1B = 0;

    TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt

    OCR1A = 25 - 1;              // compare match register 16MHz/64(prescaler)/1000(Hz)
	
    TCCR1B |= (1 << WGM12);   // CTC mode - "Clear timer on compare match."
    TCCR1B |= (1 << CS11) | (1 << CS10);    // 64 prescaler (Divide clock frequency by prescaler)
	
    TCNT1  = 0;
    interrupts();             // enable all interrupts	
}
// ---------------------------------------------------------------------------
// 0.1ms Timer Interrupt!
// ---------------------------------------------------------------------------
ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
	at_PwmTick = true; // 0.1ms * 100 Tick PWM Cycle = 10MS PWM Period
	
	at_InterruptCount++;
	if (at_InterruptCount == 10) // 1 MS
	{
		at_InterruptCount = 0;
		at_MsCount++;
		if (at_MsCount == 100)
		{
			at_MsCount = 0;
			at_LedTick = true;

			at_Ms100Count++;
			if (at_Ms100Count == 10)
			{
				at_Ms100Count = 0;
			}
		}
	}
}
// ---------------------------------------------------------------------------